<template>
  <div class="facebook" @click="login">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { useGlobalStore } from "~/store/global";
import * as MITO from "@zhj1214/qdjk-web";

const $emit = defineEmits(["success", "error"]);
const globalStore = useGlobalStore();

const facebookInit = () => {
  try {
    window.FB?.init({
      appId: globalStore.facebookAppId, // BD生产
      // appId: '303778625994525', // shawn 个人测试
      autoLogAppEvents: true,
      xfbml: true,
      version: "v15.0",
    });
  } catch (error) {
    MITO.log({
      message: `facebook 加载失败: ${error}`,
      tag: "facebook加载失败",
      level: "high",
      ex: "手动",
    });
  }
};

// 手动加载
const initAuth2 = () => {
  const ele = document.createElement("script");
  ele.src = getOssFileUrl({
    u: "/file/auth2/sdk.js",
  }).u;
  document.body.appendChild(ele);

  ele.onload = () => {
    facebookInit();
  };

  ele.onerror = () => {
    console.log("facebook load error");
  };
};

/**
 * @description: 手动加在script脚本,失败会重试 3 次
 */
loadScript(
  "https://connect.facebook.net/en_US/sdk.js",
  (val: any) => {
    console.log("-facebook-loadScript--加载完成", val);
    if (val) {
      facebookInit();
    } else {
      initAuth2();
    }
  },
  true,
  false
);

onMounted(() => {});

const login = () => {
  try {
    window.FB?.login(
      (params: any) => {
        if (params.status === "unknown") {
          $emit("error", params);
        } else {
          window.FB?.api(
            "/me",
            { fields: "email,name" },
            function (response: any) {
              console.log("face Book 授权信息:", response);
              if (!response) response = {};
              const success = { ...params, ...response };
              $emit("success", success);
            }
          );
        }
      },
      { scope: "email" }
    );
  } catch (error) {
    console.log("facebook login error", error);
    MITO.log({
      message: `facebook login error 登录失败: ${error}`,
      tag: "facebook登录失败",
      level: "high",
      ex: "手动",
    });
  }
};
</script>

<style lang="scss" scoped>
.facebook {
  position: relative;
}
</style>
